<template>
  <div>
    <!-- 面包屑导航 -->
    <!-- <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <bread>
      <span slot="second">权限管理</span>
      <span slot="third">角色列表</span>
    </bread>
    <el-card>
      <!-- 添加角色区 -->
      <el-row>
        <el-col>
          <el-button @click="addRolebtn">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="getAllRolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" >
          <template v-slot="scrop">
            <el-row v-for="item1 in scrop.row.children" :key="item1.id" class="borderBottom borderTop vcenter">
              <!-- 渲染一级 -->
                <el-col :span="5">
                   <el-tag closable @close="removeTagById(scrop.row,item1.id)"> {{item1.authName}}</el-tag>
                   <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级三级 -->
                <el-col :span="19">
                  <el-row v-for="item2 in item1.children" :key="item2.id" class="borderBottom borderTop vcenter">
                    <el-col :span="6">
                      <el-tag type="success" closable @close="removeTagById(scrop.row,item2.id)"> {{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                        <!-- 是tag重复不是列重复 -->
                          <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeTagById(scrop.row,item3.id)"> {{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
            </el-row>

          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" class="btn">
          <template v-slot="scrop">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scrop.row.id)"
            >编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scrop.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scrop.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑用户框 -->
    <el-dialog title="您需要修改的角色" :visible.sync="editRoleVisible" width="50%" @close="editRoleReset">
      <span slot="footer" class="dialog-footer">
        <el-form :model="editRoleForm" :rules="addRoleRules" ref="editRoleRef" label-width="100px">
          <el-form-item label="用户名" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleconFirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @close="addRoleReset">
      <!-- 内容 -->
      <el-form :model="addRole" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
        <el-form-item label="用户名" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible=false">取 消</el-button>
        <el-button type="primary" @click="addRoleconFirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限区域 -->
      <el-dialog title="分配权限" :visible.sync="setRightVisible" width="50%" @close="setRightDialogClosed">
      <!-- 内容 -->
      <!-- 树形控制控件 -->
      <el-tree :data="showRightList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defkeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightVisible=false">取 消</el-button>
        <el-button type="primary" @click="setRightConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Bread from '../../base/breadcrumb'
export default {
  components: {
    bread: Bread
  },
  data() {
    return {
      // 所有角色数据
      getAllRolesList: [],
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      addRoleVisible: false,
      editRoleVisible: false,
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3-10位', trigger: 'blur' }
        ]
      },
      editRoleForm: {},
      setRightVisible: false.error,
      showRightList: [],
      // 树形控件绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defkeys: [],
      // 即将分配权限的id，给权限赋值用
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.getAllRolesList = res.data
    },
    addRolebtn() {
      this.addRoleVisible = true
    },
    addRoleconFirm() {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户请求
        const { data: res } = await this.$http.post('roles', this.addRole)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        } else {
          this.$message.success('添加角色成功')
          this.addRoleVisible = false
          this.getRolesList()
        }
      })
    },
    addRoleReset() {
      this.$refs.addRoleRef.resetFields()
    },
    async editRole(id) {
      this.editRoleVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询数据失败')
      } else {
        this.editRoleForm = res.data
      }
    },
    editRoleconFirm() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户请求
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
        if (res.meta.status !== 200) {
          this.$message.error('修改角色失败')
        } else {
          this.$message.success('修改角色成功')
          this.editRoleVisible = false
          this.getRolesList()
        }
      })
    },
    editRoleReset() {
      this.$refs.editRoleRef.resetFields()
    },
    async removeRoleById(id) {
      const comfirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (comfirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    async removeTagById(role, rightsId) {
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('你已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败')
        }role.children = res.data
      }
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.showRightList = res.data
      this.setRightVisible = true
      this.getLeafKeys(role, this.defkeys)
    },
    // 递归获取defkeys
    getLeafKeys(node, arr) {
      // 三级id没有children所以直接return push到数组里
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClosed() {
      this.defkeys = []
    },
    async setRightConfirm() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idstr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idstr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.btn {
  display: flex;
}
.el-tag{
  margin: 7px;
}
.borderTop{
  border-top: 1px solid #eee;
}
.borderTop:nth-child(1){
  border-top: 1px solid #eee;
}
.borderBottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
